import React, { useEffect } from 'react'
import queryString from 'querystring'
import WNavBar from '@components/global/navBar'
// @ts-ignore
import Styles from './index.scss'
import { Toast } from 'antd-mobile';
import Router from 'next/router'
import { getQQUserInfo } from '@store/oauth/actions'
import { useDispatch } from 'react-redux'
// @ts-ignore
import QQIcon from '../../../icons/qq.svg'

const OAuthQQ = () => {

  const dispatch = useDispatch()

  const getAccessToken = () => {
    const { hash } = window.location
    if (hash) {
      const query = queryString.parse(hash)
      const accessToken = query['#access_token'] as string
      // @ts-ignore
      dispatch(getQQUserInfo(accessToken)).then(() => {
        Toast.success('登录成功', 1, () => {
          Router.replace('/OAuth')
        })
      }).catch(() => {
        Toast.fail('登录失败', 1, () => {
          Router.replace('/OAuth')
        })
      })
    }
  }

  useEffect(getAccessToken, [])

  return (
    <WNavBar title="OAuth">
      <div className={`${Styles['set-oauth-qq']} w-flex-center`}>
        <QQIcon width="100" height="100" fill="#E3091D" />
        <span className={Styles.text}>登录中...</span>
      </div>
    </WNavBar>
  )
}

OAuthQQ.getInitialProps = async () => {
  return {}
}

export default OAuthQQ
